﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Frame;
using System.Threading;
using System.IO;

namespace VideoFileOrganization.MergeFolders
{
    public partial class MergeFoldersFrm : BaseFrm
    {
        // 在线程中操作 更新界面的委托
        private delegate void IniUiDelegate();

        protected string TargetPath = string.Empty;
        public MergeFoldersFrm()
        {
            InitializeComponent();
            this.Text = "合并文件夹";
            this.Index = 3;
            this.TabImage = Properties.Resources.合并文件夹;
            dgSubDir.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
        }

        protected override void IniUi()
        {
            dgSubDir.Rows.Clear();

            if (!Directory.Exists(RootPath)) return;
            // 获取目录对象
            DirectoryInfo directory = new DirectoryInfo(RootPath);
            // 获取子文件夹
            DirectoryInfo[] subDirectories = directory.GetDirectories();

            foreach (DirectoryInfo dir in subDirectories)
            {
                // 获取子文件夹
                DirectoryInfo[] subs = dir.GetDirectories();
                //如果没有子文件夹就跳过
                //if (subs.Count() <= 0) continue;
                dgSubDir.Rows.Add();
                int row = dgSubDir.RowCount - 1;
                dgSubDir.Rows[row].HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleLeft;
                dgSubDir.Rows[row].Cells[0].Value = true;
                dgSubDir.Columns[0].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
                dgSubDir.Rows[row].Cells[1].Value = Path.GetFileName(dir.Name);
                dgSubDir.Rows[row].Cells[2].Value = dir.FullName;
            }
            //最后一行用于全选
            dgSubDir.Rows.Add();
            int end_row = dgSubDir.RowCount - 1;
            dgSubDir.Rows[end_row].HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleLeft;
            dgSubDir.Rows[end_row].Cells[0].Value = true;
            dgSubDir.Columns[0].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
            dgSubDir.Rows[end_row].Cells[1].Value = "";
            dgSubDir.Rows[end_row].Cells[1].ReadOnly = true;
            dgSubDir.Rows[end_row].Cells[2].Value = "";
            dgSubDir.Rows[end_row].Cells[2].ReadOnly = true;
            dgSubDir.Columns[0].Width = 35;
        }

        protected override void ApplyButton()
        {


            List<string> PathList = new List<string>();

            for (int i = 0; i < dgSubDir.RowCount - 1; i++)
            {
                object cellValue = dgSubDir.Rows[i].Cells[0].Value;
                if (cellValue != null && cellValue.Equals(true))
                {
                    PathList.Add(dgSubDir.Rows[i].Cells[2].Value.ToString());
                }
                else
                {
                    continue;
                }
            }
            if (PathList.Count <= 0) return;

            MergeFolderFrm frm = new MergeFolderFrm(Path.GetFileName(PathList[0]));
            if (frm.ShowDialog() == DialogResult.OK)
            {
                TargetPath = Directory.GetParent(PathList[0]).FullName + @"\" + frm.MergeFolderName;
            }
            else
            {
                return;
            }

            ParameterizedThreadStart thread = new ParameterizedThreadStart(MergeFoldersThread);
            Thread th = new Thread(thread);
            th.Start(PathList);          
        }

        private void MergeFoldersThread(Object obj)
        {
            Utility.LoadingForm w = new Utility.LoadingForm();
            Thread t = new Thread(() =>
            {
                w.ShowDialog();
            });
            t.Start();
            List<string> PathList = (List<string>)obj;
            MergeFolders(PathList.ToArray(), TargetPath);
            DirectoryHelper.DeleteEmptyFolders(Directory.GetParent(TargetPath).FullName);
            t.Abort();
            Invoke(new IniUiDelegate(IniUi));
        }

        private void MergeFolders(string[] folderPaths, string destinationFolder)
        {
            if (!Directory.Exists(destinationFolder))
            {
                // 创建目标文件夹
                Directory.CreateDirectory(destinationFolder);
            }

            // 遍历每个文件夹路径
            foreach (string folderPath in folderPaths)
            {
                if (destinationFolder == folderPath)
                    continue;
                // 遍历文件夹中的文件和子文件夹
                foreach (string filePath in Directory.GetFiles(folderPath, "*", SearchOption.AllDirectories))
                {
                    // 获取文件的相对路径
                    string relativePath = filePath.Substring(folderPath.Length + 1);

                    // 拼接目标文件路径
                    string destinationFilePath = Path.Combine(destinationFolder, relativePath);

                    // 创建目标文件的父文件夹
                    Directory.CreateDirectory(Path.GetDirectoryName(destinationFilePath));

                    // 复制文件到目标文件夹
                    //File.Copy(filePath, destinationFilePath, true);
                    int fileIndex = 1;
                    while (File.Exists(destinationFilePath))
                    {
                        string newFileName = $"{Path.GetFileNameWithoutExtension(filePath)}_{fileIndex}{Path.GetExtension(filePath)}";
                        destinationFilePath = Path.Combine(destinationFolder, newFileName);
                        fileIndex++;
                    }
                    File.Move(filePath, destinationFilePath);
                }
                // 删除源文件夹
                //Directory.Delete(folderPath, true);
            }
            
        }

        private void dgSubDir_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            // 检查点击的是否是复选框列
            if (e.ColumnIndex == 0 && e.RowIndex == dgSubDir.Rows.Count - 1)
            {
                // 检查点击的单元格是否是复选框
                if (dgSubDir[e.ColumnIndex, e.RowIndex] is DataGridViewCheckBoxCell)
                {
                    DataGridViewCheckBoxCell cell = dgSubDir[e.ColumnIndex, e.RowIndex] as DataGridViewCheckBoxCell;

                    // 切换最后一行的复选框状态
                    cell.Value = !(bool)cell.Value;

                    // 遍历所有行，设置第一列的复选框状态与最后一行相同
                    foreach (DataGridViewRow row in dgSubDir.Rows)
                    {
                        if (row.IsNewRow) continue; // 跳过新增行
                        row.Cells[0].Value = cell.Value;
                    }
                }
            }
            else if(e.ColumnIndex == 0 && e.RowIndex != dgSubDir.RowCount-1 )
            {
                bool allChecked = true;
                foreach (DataGridViewRow row in dgSubDir.Rows)
                {
                    if (row.Index == dgSubDir.RowCount - 1) continue; // 跳过新增行
                    if (!(bool)row.Cells[e.ColumnIndex].Value)
                    {
                        allChecked = false;
                        break;
                    }
                }
                // 如果所有行的第一列复选框都选中，则选中最后一行的第一列复选框
                // 如果不是，则取消选中最后一行的第一列复选框
                if (allChecked)
                {
                    dgSubDir.Rows[dgSubDir.Rows.Count - 1].Cells[e.ColumnIndex].Value = true;
                }
                else
                {
                    dgSubDir.Rows[dgSubDir.Rows.Count - 1].Cells[e.ColumnIndex].Value = false;
                }
            }

            
        }
    }
}
